package com.mjk.common.web.getway.restful.filter;

import com.mjk.common.web.getway.restful.filter.gzip.GZipResponseWrapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 从新包装httpservletrequest  解决request.getinputstream只能获取一次的问题
 * @author mjk
 * 
 */

public class RequestFilter implements Filter{
	@Override
	public void destroy() {
		//do noting
	}

	public void doFilter(ServletRequest req, ServletResponse rsp,
						 FilterChain chain) throws IOException, ServletException {
		if(req instanceof HttpServletRequest requst){
			//判断是否需要压缩
			String acceptEncoding =requst.getHeader("Accept-Encoding");
			if(acceptEncoding != null && acceptEncoding.toLowerCase().indexOf("gzip") != -1){
				HttpServletResponse response =(HttpServletResponse)rsp;
				GZipResponseWrapper gzipResp = new GZipResponseWrapper(response);
				
				chain.doFilter(new HttpRequest((HttpServletRequest)req), gzipResp);//doFilter,使用自定义的response
				gzipResp.finishResponse();//输出压缩数据
			}else{//不进行压缩
				chain.doFilter(new HttpRequest((HttpServletRequest)req), rsp);
			}
		}else{	
			chain.doFilter(req, rsp);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//do noting
	}

}
